//
//  VideoViewController.m
//  Connotation
//
//  Created by LZXuan on 15-7-14.
//  Copyright (c) 2015年 轩哥. All rights reserved.
//
#import <MediaPlayer/MediaPlayer.h>
#import "VideoViewController.h"
#import "JHRefresh.h"
#import "VideoCell.h"
#import "VideoModel.h"
#define  kCellID @"VideoCell"
#define kScreenSize [UIScreen mainScreen].bounds.size
@interface VideoViewController ()
{
     MPMoviePlayerViewController*_moviePlayer;
}
@end

@implementation VideoViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets=NO;
    self.isRefreshing=NO;
    self.isLoadingMore=NO;
    self.currentPage=0;
    self.max_timestamp=@"-1";
    [self createTableView];
    [self createRequest];
    [self loadDataWithPage:self.currentPage count:30];
    [self createRefreshView];
    
}


#pragma mark - 表格
- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height-64-49) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"VideoCell" bundle:nil] forCellReuseIdentifier:kCellID];
}
#pragma mark - 下载对象
- (void)createRequest {
    _manager = [AFHTTPRequestOperationManager manager];
    //设置 响应 格式 二进制 不解析
    _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //数据源数组
    self.dataArray = [[NSMutableArray alloc] init];
}
#pragma mark - 刷新
- (void)createRefreshView {
    
    __weak typeof(self)weakSelf = self;
    
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        //只要下拉刷新就会 回调这个block
        if (weakSelf.isRefreshing) {
            //正在刷新 直接返回
            return ;
        }
        weakSelf.isRefreshing = YES;
        weakSelf.currentPage = 0;
        weakSelf.max_timestamp = @"-1";
        //下拉 刷新  第 0 页 30条
        [weakSelf loadDataWithPage:weakSelf.currentPage count:30];
    }];
    
    //上拉加载
    [self.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        //上拉 会 回调这个block
        if (weakSelf.isLoadingMore) {
            return ;
        }
        weakSelf.isLoadingMore = YES;
        weakSelf.currentPage++;//页码+1
        //上拉加载的时候max_timestamp 应该是最后一条数据的时间
        VideoModel *model = [weakSelf.dataArray lastObject];
        weakSelf.max_timestamp = model.update_time;
        [weakSelf loadDataWithPage:weakSelf.currentPage count:15];
        
    }];
}

- (void)endRefreshing {
    if (self.isRefreshing) {
        self.isRefreshing = NO;
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultSuccess];
    }
    if (self.isLoadingMore) {
        self.isLoadingMore = NO;
        [self.tableView footerEndRefreshing];
    }
}
#pragma mark - 下载数据解析数据
- (void)loadDataWithPage:(NSInteger)page count:(NSInteger)count {
    NSString *url = [NSString stringWithFormat:kContentUrl,kVideos,page,count,self.max_timestamp];
    
    __weak typeof(self) weakSelf = self;
    
    [_manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if (responseObject) {
            if (weakSelf.currentPage == 0 ) {
                [weakSelf.dataArray removeAllObjects];
            }
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSArray *itemArr = dict[@"items"];
            
            for (NSDictionary*itemDict in itemArr) {
                
                VideoModel *model= [[VideoModel alloc] init];
                [model setValuesForKeysWithDictionary:itemDict];
                
                [weakSelf.dataArray addObject:model];
            }
            
            [weakSelf.tableView reloadData];
            [weakSelf endRefreshing];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [weakSelf endRefreshing];
    }];
    
}
#pragma mark - TableView协议
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    VideoCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID forIndexPath:indexPath];
    VideoModel *model = self.dataArray[indexPath.row];
    
    [cell showDataWithModel:model];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 140;
    
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoModel*model=self.dataArray[indexPath.row];
    [self createVideoWithPath:model.vplay_url];
    
}
#pragma mark 视频播放
-(void)createVideoWithPath:(NSString*)path{
    
    NSURL *url=nil;
    if ([path hasPrefix:@"http://"]||[path hasPrefix:@"https://"]) {
        url=[NSURL URLWithString:path];
    }
    //注册一个观察者对象 监听 视频是否播放完毕（1.点击done 2.正常播放3.异常）
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playVideoBack:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    
    
    if (!_moviePlayer) {
        
        _moviePlayer=[[MPMoviePlayerViewController alloc]initWithContentURL:url];
        _moviePlayer.moviePlayer.shouldAutoplay=YES;
        
    }
    
    [_moviePlayer.moviePlayer play];
    
    
    //模态跳转
    [self presentViewController:_moviePlayer animated:YES completion:nil];
    //或者
    //[self presentMoviePlayerViewControllerAnimated:_moviePlayer];
}
-(void)playVideoBack:(NSNotification*)nf{
    
    NSLog(@"播放完毕 info:%@",nf.userInfo);
    
    NSInteger type=[nf.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey]integerValue];
    if (type==0) {
        NSLog(@"正常");
    }else if (type==1){
        NSLog(@"异常");
    }else if (type==2){
        NSLog(@"点击Done 返回");
    }
    
    if (_moviePlayer) {
        [_moviePlayer.moviePlayer stop];
        _moviePlayer=nil;
    }
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    
    
    [_moviePlayer dismissViewControllerAnimated:YES completion:nil];
    
}

@end
